<script setup>
import {v4} from 'uuid'

//定义参数
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  defaultItemValue: {
    type: Object
  },
  formConfig: {
    type: Object
  }
})

//定义发射事件
const emit = defineEmits(['update:modelValue'])

//新增项
const handleAdd = () => {
  emit('update:modelValue', [...props.modelValue, {...props.defaultItemValue, key: v4()}])
}

//删除文件
const handleDelete = (item) => {
  emit('update:modelValue', props.modelValue.filter(i => i !== item))
}

</script>

<template>
  <div class="form-array">
    <!-- 新增按钮 -->
    <div class="top">
      <el-button icon="Plus" text bg @click="handleAdd">新增项</el-button>
    </div>

    <!-- 文件列表 -->
    <template v-for="(item, index) in modelValue" :key="item.key">
      <div class="form-item">
        <!-- 文件预览 -->
        <view class="left">
          <div class="index">{{ index + 1 }}.</div>
          <div class="left-form">
            <app-form v-model="modelValue[index]" :form-config="formConfig" :form-props="{labelWidth: '50'}" hide-btn/>
          </div>
        </view>

        <!-- 删除图片 -->
        <div class="delete-box" @click="handleDelete(item)">
          <el-icon>
            <CloseBold class="delete-icon"/>
          </el-icon>
        </div>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.form-array, .form-item .left {
  gap: $spacing-4;
}

.form-array {
  @include flex-box(false, true);
  width: 100%;

  .top {
    width: 200px;
    margin-bottom: $spacing-3;
  }

  .form-item, .left {
    @include flex-box;
  }

  .form-item {
    margin-left: -70px;
    align-items: center;
    justify-content: space-between;

    .left {
      width: 100%;

      .left-form {
        width: 85%;
      }
    }

    .delete-box {
      @include flex-box(true);
      width: 40px;
      height: 40px;
      color: $red;
      cursor: pointer;

      &:hover {
        background: $light-bg;
      }
    }
  }
}
</style>
